import Pagination from '@/components/Pagination'
import { format } from 'date-fns'
import { useEffect, useState } from 'react'
import { videoService, audioService } from '@/services'
import { CustomDialog } from '@/components/CustomDialog'
interface HistoryState {
  text: string
  created_at: number
  result: {
    data: string
  }
}

interface HistoryDialogProps {
  inGraphic?: boolean
  open: boolean
  onOpenChange: (open: boolean) => void
  onSelectHistory: (v: any) => void
}

const ITEMS_PER_PAGE = 5 // 每页显示的历史记录数量

export function TextHistoryDialog({
  inGraphic = false, // 是否在图文创作中
  open,
  onOpenChange,
  onSelectHistory,
}: HistoryDialogProps) {
  const [currentPage, setCurrentPage] = useState(1)
  const [data, setData] = useState<HistoryState[]>([])
  const [totalPages, setTotalPages] = useState(0)
  const getList = () => {
    const getApi = inGraphic
      ? audioService.graphicCreationListForHistory
      : videoService.getBroadcastList
    getApi({
      pageNum: currentPage,
      pageSize: ITEMS_PER_PAGE,
    }).then((res: any) => {
      const result: any = res.data
      if (inGraphic) {
        result.forEach((item: any) => {
          item.result.data =
            item?.graphic_creation_offical_account_texts[0]?.result?.data
        })
      }
      setData(result)
      setTotalPages(Math.ceil(res.total / ITEMS_PER_PAGE))
    })
  }
  useEffect(() => {
    if (open) {
      getList()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, open])

  const handleClose = () => {
    setCurrentPage(1)
    onOpenChange(false)
  }
  return (
    <CustomDialog title="历史记录" open={open} onOpenChange={handleClose}>
      <div className="py-4 h-[520px] max-h-[75vh] overflow-y-auto my-scrollbar">
        {data.map((item, index) => (
          <div
            key={index}
            className="py-4 px-4 border-b cursor-pointer hover:bg-gray-50 last:border-b-0"
            onClick={() => onSelectHistory(item)}
          >
            <div className="text-gray-400 text-xs mb-2">
              生成时间：{format(item.created_at, 'yyyy年MM月dd日')}
            </div>
            <div className="text-sm line-clamp-2">{item?.result?.data}</div>
          </div>
        ))}
        {data.length === 0 && currentPage === 1 && (
          <div className="text-center text-gray-500 py-8">暂无历史记录</div>
        )}
      </div>

      {data.length > 0 && (
        <Pagination
          className="justify-end"
          isMini={true}
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
      )}
    </CustomDialog>
  )
}
